package com.supor.aiot.mine.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.baseconfig.common.utils.ThreadUtils;
import com.supor.aiot.common.utils.AnimationUtil;
import com.supor.aiot.mine.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: FeedbackPop <br>
 * 作者: lei <br>
 * 日期: 2020/12/28 <br>
 */
public class FeedbackPop {

    static PopupWindow questionPopupWindow;
    static PopupWindow photoPopupWindow;
    Handler handler;
    private WeakReference<Activity> activityReference;
    FeedbackCallback callback;

    private static volatile FeedbackPop instance;
    private float alpha;
    int duration = 300;
    int sleepTime = duration / 100;

    int type = 0;
    ListView listView;

    ArrayList<String> dataList;
    ArrayAdapter<String> adapter;


    public static FeedbackPop getInstance() {
        if (instance == null) {
            instance = new FeedbackPop();
        }
        return instance;
    }

    private FeedbackPop() {
        dataList = new ArrayList<>();
    }

    public void init(Activity activity, FeedbackCallback callback) {
        handler = new Handler(activity.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    AnimationUtil.backgroundAlpha(activityReference.get(), (float) msg.obj);
                }
            }
        };
        this.callback = callback;
        activityReference = new WeakReference<>(activity);
        initPop(activity);
    }

    public void setCallback(FeedbackCallback callback) {
        this.callback = callback;
    }

    private void initPop(Activity activity) {
        // 问题类型的popwindow
        View view = LayoutInflater.from(activity).inflate(R.layout.pop_feedback_request_type, null);
        setPopupWindow(questionPopupWindow = new PopupWindow(), view);

        listView = view.findViewById(R.id.list_view);
        adapter = new ArrayAdapter<String>(activity,
                R.layout.item_feedback_question, R.id.tv_text, dataList);
        // 给组件设置数据适配器
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view1, position, id) -> {
            if (callback != null) {
                callback.onQuestionTypeItem(position);
                dismissQuestionPop();
            }
        });
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        tvCancel.setOnClickListener(v -> dismissQuestionPop());

        // 点击图片时popwindow
        View photoView = LayoutInflater.from(activity).inflate(R.layout.pop_feedback_photo, null);
        setPopupWindow(photoPopupWindow = new PopupWindow(), photoView);

        TextView tvPreview = photoView.findViewById(R.id.tv_preview);
        tvPreview.setOnClickListener(v -> {
            if (callback != null) {
                callback.onPreview();
                dismissPhotoPop();
            }
        });
        TextView tvDelete = photoView.findViewById(R.id.tv_delete);
        tvDelete.setOnClickListener(v -> {
            if (callback != null) {
                callback.onDelete();
                dismissPhotoPop();
            }
        });
        TextView tvCancel_ = photoView.findViewById(R.id.tv_cancel);
        tvCancel_.setOnClickListener(v -> dismissPhotoPop());
    }

    /**
     * 设置popwindow属性
     *
     * @param popupWindow
     * @param view
     */
    private void setPopupWindow(PopupWindow popupWindow, View view) {
        popupWindow.setContentView(view);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setFocusable(false);// 解决点击view重新打开popwindow的问题
        popupWindow.setOutsideTouchable(true);// 点击外部popupwindow消失
        popupWindow.setAnimationStyle(R.style.privacy_popup_window_anim);
        // 退出popupWindow时取消暗背景
        popupWindow.setOnDismissListener(this::processDismiss);
    }

    // popwindow消失时背景同步变化
    private void processDismiss() {
        ThreadUtils.execute(() -> {
            while (alpha < 1f) {
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                alpha += 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        });
    }

    public void showQuestionPop(Activity activity, View rootView) {
        if (questionPopupWindow == null) {
            initPop(activity);
        }
        adapter = new ArrayAdapter<String>(activity,
                R.layout.item_feedback_question, R.id.tv_text, dataList);
        listView.setAdapter(adapter);
        questionPopupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        showAnimation();
    }

    public void showPhotoPop(Activity activity, View rootView) {
        if (photoPopupWindow == null) {
            initPop(activity);
        }
        photoPopupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        showAnimation();
    }

    private void showAnimation() {
        alpha = 1f;
        ThreadUtils.execute(() -> {
            while (alpha > 0.5f) {
                try {
                    // 根据弹出动画时间和减少的透明度计算时间
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                // 每次减少0.005，精度越高，变暗的效果越流畅
                alpha -= 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        });
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public boolean isQuestionPopShow() {
        return questionPopupWindow != null && questionPopupWindow.isShowing();
    }

    public boolean isPhotoPopShow() {
        return photoPopupWindow != null && photoPopupWindow.isShowing();
    }

    public void dismissQuestionPop() {
        if (questionPopupWindow != null && questionPopupWindow.isShowing()) {
            questionPopupWindow.dismiss();
        }
    }

    public void dismissPhotoPop() {
        if (photoPopupWindow != null && photoPopupWindow.isShowing()) {
            photoPopupWindow.dismiss();
        }
    }

    public ArrayList<String> getDataList() {
        return dataList;
    }

    public void setDataList(ArrayList<String> dataList) {
        this.dataList = dataList;
    }

    public interface FeedbackCallback {
        /**
         * 选择问题类型
         * @param position 点击位置
         */
        void onQuestionTypeItem(int position);

        /**
         * 预览图片
         */
        void onPreview();

        /**
         * 删除图片
         */
        void onDelete();
    }
}
